package com.ysx.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysx.comment.dto.CommentDto;
import com.ysx.comment.dto.CommentLikeDto;
import com.ysx.comment.dto.CommentSaveDto;
import com.ysx.comment.ducument.ApCommentDocument;
import com.ysx.comment.ducument.ApCommentLikeDocument;
import com.ysx.comment.mapper.ApCommentMapper;
import com.ysx.comment.pojo.ApComment;
import com.ysx.comment.service.ApCommentService;
import com.ysx.comment.vo.CommentVo;
import com.ysx.common.pojo.StatusCode;
import com.ysx.common.utils.RequestHeaderInfoUtils;
import com.ysx.exception.ToutiaoException;
import com.ysx.user.feign.ApUserFeign;
import com.ysx.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * APP评论信息表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2021-10-08
 */
@Service
public class ApCommentServiceImpl extends ServiceImpl<ApCommentMapper, ApComment> implements ApCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApUserFeign apUserFeign;

    @Override
    public void saveToMongo(CommentSaveDto commentSaveDto) throws Exception{
        //1.校验数据是否符合要求
        if(StringUtils.isEmpty(commentSaveDto.getContent()) || commentSaveDto.getArticleId()==null){
            throw new ToutiaoException("评论内容不能为空");
        }
        //2.判断当前用户是否已经登录
        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();
        if("0".equals(userInfo)){
            throw new ToutiaoException(StatusCode.NEED_LOGIN.code(),StatusCode.NEED_LOGIN.message());
        }
        //3.设置数据 添加到 mongo中
        ApCommentDocument entity = new ApCommentDocument();
        entity.setLikes(0);
        entity.setReplys(0);
        entity.setContent(commentSaveDto.getContent());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedTime(LocalDateTime.now());
        entity.setArticleId(commentSaveDto.getArticleId());
        //entity.setChannelId();
        entity.setUserId(Integer.valueOf(userInfo));
        ApUser apUser = apUserFeign.findById(Integer.valueOf(userInfo)).getData();
        if(apUser!=null){
            entity.setNickName(apUser.getName());
            entity.setHeadImage(apUser.getImage());
        }
        //需要远程调用获取到登录的用户的ap_user对象 中的 头像和 昵称
        mongoTemplate.insert(entity);
    }


    /**
     * 根据文章id 和 操作类型 进行更新点赞数量 记录行为
     * @param commentLikeDto
     */
    @Override
    public void like(CommentLikeDto commentLikeDto) throws Exception {
        //1.校验数据是否符合要求
        if(StringUtils.isEmpty(commentLikeDto.getCommentId()) || commentLikeDto.getOperation()==null){
            throw new ToutiaoException("点赞的评论的ID 和操作类型不能为null");
        }
        if(commentLikeDto.getOperation()>1 || commentLikeDto.getOperation()<0){
            throw new ToutiaoException("operation操作范围只能是0-1");
        }
        //2.判断当前用户是否已经登录
        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();
        if(userInfo.equals("0")){
            throw new ToutiaoException(StatusCode.NEED_LOGIN.code(),StatusCode.NEED_LOGIN.message());
        }
        //3.设置数据 添加,删除到 mongo中
        if(commentLikeDto.getOperation()==1){

            //条件判断 如果有点赞了就不用再点赞了
            Query query2 = Query.query(Criteria.where("userId").is(Integer.valueOf(userInfo)).and("commentId").is(commentLikeDto.getCommentId()));
            List<ApCommentLikeDocument> apCommentDocumentLikes = mongoTemplate.find(query2, ApCommentLikeDocument.class);
            if(apCommentDocumentLikes!=null && apCommentDocumentLikes.size()>0){
                return;
            }

            ApCommentLikeDocument entity = new ApCommentLikeDocument();
            entity.setUserId(Integer.valueOf(userInfo));
            entity.setCommentId(commentLikeDto.getCommentId());
            mongoTemplate.save(entity);

            //评论的数量+1   select * from comment where id=?  update
            /*ApCommentDocument apCommentDocument = mongoTemplate.findById(commentLikeDto.getCommentId(), ApCommentDocument.class);
            apCommentDocument.setLikes(apCommentDocument.getLikes()+1);
            mongoTemplate.save(apCommentDocument);*/

            Query query = Query.query(Criteria.where("_id").is(commentLikeDto.getCommentId()));
            Update update = new Update();
            update.inc("likes");//+1
            mongoTemplate.findAndModify(query,update,ApCommentDocument.class);

        }else{
            //取消点赞 delete from xxx where user_id=? and commentId=?
            Query query = Query.query(Criteria.where("userId").is(Integer.valueOf(userInfo)).and("commentId").is(commentLikeDto.getCommentId()));
            mongoTemplate.findAllAndRemove(query,ApCommentLikeDocument.class);

            //点赞数-1
            Query query1 = Query.query(Criteria.where("_id").is(commentLikeDto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);//-1
            mongoTemplate.findAndModify(query1,update,ApCommentDocument.class);
        }
    }


    /**
     * 分页查询 mongodb  返回评论列表展示10条数据限制
     *
     * @return
     */
    @Override
    public List<CommentVo> loadPage(CommentDto commentDto) {
        //1查询评论列表
        // select * from comment where createtime < ? and article_id=? order by createtime desc limit 10
        LocalDateTime minDate = commentDto.getMinDate();

        //一页最后一条记录的时间 作为查询条件
        if(minDate==null){
            minDate=LocalDateTime.now();
        }


        Query query = Query.query(
                Criteria.where("articleId").is(commentDto.getArticleId())
                        .and("createdTime").lt(minDate)
        );

        //排序
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));

        //限制（分页） 10条记录
        query.limit(10);


        String userInfo = RequestHeaderInfoUtils.getHeaderUserId();


        List<ApCommentDocument> apCommentDocuments = mongoTemplate.find(query, ApCommentDocument.class);

        //2查询当前用户对应的点赞记录 select * from likedocument where userId=? and commentId in (apCommentDocuments的评论ID)
        List<String> ids = apCommentDocuments.stream().map(document -> document.getId()).collect(Collectors.toList());

        List<ApCommentLikeDocument> apCommentLikeDocuments = null;
        //真实的用户才能点赞的，所以只查询真实用户的点赞记录
        if(!userInfo.equals("0")){
            Query query1 = Query.query(
                    Criteria.where("userId").is(Integer.valueOf(userInfo))
                            .and("commentId").in(ids)
            );
            apCommentLikeDocuments = mongoTemplate.find(query1, ApCommentLikeDocument.class);
        }


        //3组合 设置标记是否被点赞   返回voList
        List<CommentVo> commentVosList =new ArrayList<CommentVo>();
        commentVosList = JSON.parseArray(JSON.toJSONString(apCommentDocuments), CommentVo.class);
        //遍历评论记录
        for (CommentVo commentVo : commentVosList) {
            //没有评论点赞记录 就不需要返回点赞状态
            if(apCommentLikeDocuments!=null) {
                //遍历评论点赞记录
                for (ApCommentLikeDocument apCommentLikeDocument : apCommentLikeDocuments) {
                    //如果当前用户点赞过评论列表中的某一篇文章 就将这篇文章的operation状态改为1(已点赞)
                    if(apCommentLikeDocument.getCommentId().equals(commentVo.getId())) {
                        commentVo.setOperation(1);
                    }
                }
            }

        }
        return commentVosList;
    }
}
